<?php
class Admin extends MY_Controller {
    
    function __construct() {
        parent::__construct();
        $this->load->library('ion_auth');
        if ( !$this->ion_auth->logged_in() || !$this->ion_auth->is_admin() ) {
            redirect('/auth');
        }
		session_start();
		$_SESSION['KCFINDER'] = array();
        $_SESSION['KCFINDER']['disabled'] = false;
    }

    function _loadTemplate($data) {
        $data['userId'] = $this->ion_auth->user()->row()->id;
        $data['coursesList'] = $this->coursesList();
        $this->load->view('admin/template', $data);	
    }
    
    /**
     * 
     */
    public function index() {
        $data['title'] = '';
        $data['template'] = 'admin/index';
        $this->_loadTemplate($data);
    }
    
    /**
     * Show only the articles of the site that are NOT related with some course
     * Used a custom query because it was not possible with grocery crud
     */
    public function articlesGeneral() {
        $this->load->helper('url');
        $this->load->library('grocery_CRUD');
        //$crud = new grocery_CRUD();
        //$crud->set_table('articles')
        // ->set_subject('Article')
        // ->columns('title', 'content', 'categories', 'courses', 'date');
        //$crud->set_relation_n_n('categories', 'articles_categories', 'categories', 'article_id', 'category_id', 'name', null, "`type` = 'article'"); 
        //$crud->where('categories.type = `article`');
        //$crud->set_relation_n_n('courses', 'courses_articles', 'courses', 'article_id', 'course_id', 'title');
        $crud = new grocery_CRUD();
        $crud->set_model('custom_query_model');
        $crud->set_table('articles');
        $crud->set_relation_n_n('categories', 'articles_categories', 'categories', 'article_id', 'category_id', 'name', null, "`type` = 'article'");
        $crud->basic_model->set_query_str(
        "SELECT `articles`.*, 
            (SELECT GROUP_CONCAT(DISTINCT categories.name) 
                FROM categories LEFT JOIN articles_categories 
                ON articles_categories.category_id = categories.id 
                WHERE articles_categories.article_id = `articles`.id 
                GROUP BY articles_categories.article_id) 
            AS categories FROM (`articles`) 
            LEFT JOIN articles_categories 
            ON articles_categories.article_id = `articles`.id 
            JOIN `categories` 
            ON articles_categories.category_id = categories.id 
            WHERE `categories`.type = 'article'");
        $crud->callback_after_insert(array($this, '_relateArticleWithUser'));
        $crud->unset_jquery();          
        $output = $crud->render();
        $data['output'] = $output;
        $data['title'] = 'Articles';
        $data['template'] = 'groceryCrud';
        $this->_loadTemplate($data);
    }
    
    /**
     * Show only the articles of the site that ARE related with some course
     * Used a custom query because it was not possible with grocery crud
     */
    public function articlesCourses() {
        $this->load->helper('url');
        $this->load->library('grocery_CRUD');
        $crud = new grocery_CRUD();
        $crud->set_model('custom_query_model');
        $crud->set_table('articles');
        $crud->set_relation_n_n('categories', 'articles_categories', 'categories', 'article_id', 'category_id', 'name', null, "`type` = 'course'");
        $crud->basic_model->set_query_str(
        "SELECT `articles`.*, 
            (SELECT GROUP_CONCAT(DISTINCT categories.name) 
                FROM categories LEFT JOIN articles_categories 
                ON articles_categories.category_id = categories.id 
                WHERE articles_categories.article_id = `articles`.id 
                GROUP BY articles_categories.article_id) 
            AS categories FROM (`articles`) 
            LEFT JOIN articles_categories 
            ON articles_categories.article_id = `articles`.id 
            JOIN `categories` 
            ON articles_categories.category_id = categories.id 
            WHERE `categories`.type = 'course'");
        $crud->callback_after_insert(array($this, '_relateArticleWithUser'));
        $crud->unset_jquery();          
        $output = $crud->render();
        $data['output'] = $output;
        $data['title'] = 'Articles';
        $data['template'] = 'groceryCrud';
        $this->_loadTemplate($data);
    }
    
    public function courses($id = NULL) {
        $this->load->helper('url');
        $this->load->library('grocery_CRUD');
        $crud = new grocery_CRUD();
        $crud->set_table('users')
            ->set_subject('New User')
            ->columns('username','email','first_name','last_name','phone','created_on','last_login','ip_adress','active');
        $crud->set_relation_n_n('users', 'users_courses', 'users', 'course_id', 'user_id', 'last_name', null, array('users.username' => 'kassy'));
        $crud->unset_jquery(); 
        $output = $crud->render();
        $data['output'] = $output;
        $data['title'] = 'Courses';
        $data['template'] = 'groceryCrud';
        $this->_loadTemplate($data);
    }
    
    public function course() {
        $this->load->helper('url');
        $this->load->library('grocery_CRUD');
        $crud = new grocery_CRUD();
        $crud->set_table('courses')
          ->set_subject('New Course')
          ->unset_columns('id');
         //->columns('title')
        // ->display_as('title','Course Title');
        //  $crud->fields('title');
        //$crud->set_relation_n_n('users', 'users_courses', 'users', 'course_id', 'user_id', 'last_name');   
        $crud->set_relation_n_n('attachments', 'courses_attachments', 'attachments', 'course_id', 'attachment_id', 'name','');
        $crud->set_relation('category_id', 'categories', 'name');
        $crud->display_as('category_id', 'Category');
        $crud->unset_jquery();
        $output = $crud->render();
        $data['output'] = $output;
        $data['title'] = 'Courses';
        $data['template'] = 'groceryCrud';
        $this->_loadTemplate($data);
    }
    
    public function classroom() {
        $this->load->helper('url');
        $this->load->library('grocery_CRUD');
        $crud = new grocery_CRUD();
        $crud->set_model('custom_query_model');
        $crud->set_table('classrooms')
            ->set_subject('New Classroom')
            ->columns('Category', 'Course', 'name', 'time', 'capacity', 'Students')
            ->unset_columns('id');
        $crud->set_relation_n_n('Students', 'classrooms_users', 'users', 'classroom_id', 'user_id', 'last_name','');
        //$crud->set_relation('course_id', 'courses', 'title');
        //$crud->set_relation('category_id', 'categories', 'name');
        $crud->basic_model->set_query_str(
                "SELECT `classrooms`.*, 
                    courses.title as Course, 
                    categories.name as Category 
                    FROM classrooms 
                    JOIN courses 
                    ON classrooms.course_id = courses.id 
                    JOIN categories 
                    ON courses.category_id = categories.id");
        
        $this->db->select('id, title');
        $this->db->from('courses');
        $query = $this->db->get();
        $finalArray = array();
        foreach ($query->result() as $row) {
            $finalArray[$row->id] = $row->title;
        }

        $crud->field_type('course_id', 'dropdown', $finalArray);
        $crud->display_as('course_id', 'Course');
        $crud->unset_jquery();
        $output = $crud->render();
        $data['output'] = $output;
        $data['title'] = 'Classrooms';
        $data['template'] = 'groceryCrud';
        $this->_loadTemplate($data);
    }
    
    public function user($operation = null) {
        $this->load->helper('url');
        $this->load->library('grocery_CRUD');
        $crud = new grocery_CRUD();
        $crud->set_table('users')->set_subject('New User');
		$crud->columns('Groups', 'username','email','first_name','last_name','phone','created_on','last_login','ip_adress','active');
		if ($operation == 'edit' || $operation == 'add') {

		} else {
			$crud->field_type('password', 'hidden');
		}

        $crud->display_as('ip_address', 'Last login from ip');
        $crud->field_type('ip_address', 'readonly');

        $crud->field_type('salt', 'hidden');
        $crud->field_type('activation_code', 'hidden');
        $crud->field_type('forgotten_password_code', 'hidden');
        $crud->field_type('forgotten_password_time', 'hidden');
        $crud->field_type('remember_code', 'hidden');
		
		$crud->set_rules('password', 'Password', 'min_length[' . $this->config->item('min_password_length', 'ion_auth') . ']|max_length[' . $this->config->item('max_password_length', 'ion_auth') . ']');
		$crud->set_rules('email', 'Email','required|valid_email');
		
		$crud->callback_column('created_on', array($this, '_datetime'));
		$crud->callback_column('last_login', array($this, '_datetime'));
		$crud->callback_field('created_on',array($this, '_datetime'));
		$crud->callback_field('last_login',array($this, '_datetime'));
		$crud->callback_before_insert(array($this, '_insert_encrypt_password_callback'));
		$crud->callback_before_update(array($this, '_edit_encrypt_password_callback'));
		$crud->callback_edit_field('password', array($this, '_decrypt_password_callback'));
		
        $crud->set_relation_n_n('Groups', 'users_groups', 'groups', 'user_id', 'group_id', 'name', '');
        $crud->unset_jquery();          
        $output = $crud->render();
        $data['output'] = $output;
        $data['title'] = 'Users';
        $data['template'] = 'groceryCrud';
        $this->_loadTemplate($data);
    }
	
	function _datetime($value, $row) {
		return @date('d M Y H:i:s', $value);
	}
	
	function _insert_encrypt_password_callback($post_array, $primary_key = null) {
		$this -> load -> model('ion_auth_model');

		$post_array['password'] = $this -> ion_auth_model -> hash_password($post_array['password']);
		$post_array['created_on'] = now();

		return $post_array;
	}
	
	function _edit_encrypt_password_callback($post_array, $primary_key = null) {
		$this -> load -> model('ion_auth_model');

		if ($post_array['password'] == 'defaultvalue') {
			unset($post_array['password']);
		} else {
			$post_array['password'] = $this -> ion_auth_model -> hash_password($post_array['password']);
		}
		return $post_array;
	}
	
	function _decrypt_password_callback($value) {
		return "<input type='password' name='password' value='defaultvalue' />";
	}
    
    public function user_groups() {
        $this->load->helper('url');
        $this->load->library('grocery_CRUD');
        $crud = new grocery_CRUD();
        $crud->set_table('groups')
          ->set_subject('Group');
        $crud->unset_jquery();          
        $output = $crud->render();
        $data['output'] = $output;
        $data['title'] = 'Groups';
        $data['template'] = 'groceryCrud';
        $this->_loadTemplate($data);
    }
    
    public function category() {
        $this->load->helper('url');
        $this->load->library('grocery_CRUD');
        $crud = new grocery_CRUD();
        $crud->set_table('categories')
            ->set_subject('New Category')
            ->unset_columns('id');
        $crud->field_type('type','enum',array('course','article'));
        $crud->unset_jquery();          
        $output = $crud->render();
        $data['output'] = $output;
        $data['title'] = 'Categories';
        $data['template'] = 'groceryCrud';
        $this->_loadTemplate($data);
    }
    
    public function attachment() {
        $this->load->helper('url');
        $this->load->library('grocery_CRUD');
        $crud = new grocery_CRUD();
        $crud->set_table('attachments')
            ->set_subject('New Attachment')
            ->unset_columns('id');
        $crud->add_fields('name','link');
        $crud->edit_fields('name','link');
        $crud->set_field_upload('link','assets/uploads/files');
        $crud->unset_jquery();          
        $output = $crud->render();
        $data['output'] = $output;
        $data['title'] = 'Attachments';
        $data['template'] = 'groceryCrud';
        $this->_loadTemplate($data);
    }

    public function comment() {
        $this->load->helper('url');
        $this->load->library('grocery_CRUD');
        $crud = new grocery_CRUD();
        $crud->set_table('comments');
        $crud->set_relation_n_n('user', 'comments_users', 'users', 'comment_id', 'user_id', 'last_name',''); 
        $crud->edit_fields('content');
        $crud->unset_add();
        $crud->unset_jquery();          
        $output = $crud->render();
        $data['output'] = $output;
        $data['title'] = 'Comments';
        $data['template'] = 'groceryCrud';
        $this->_loadTemplate($data);
    }
    
    public function coursesList() {
        /*$category = new Category();
        $category->include_related('course', '*', TRUE, TRUE)->group_by('name')->get();
        foreach($category as $c){
            echo $c->name;
            echo "<br/>------------<br/>";
            foreach($c->course as $course) {
                echo $course->title;
                echo "<br/>";
            }
        }*/
        
        $course = new Course();
        $course->include_related('category', '*', TRUE, TRUE)->order_by('category_name');
        $course->include_related('classroom', '*', TRUE, TRUE);
        $course->get();
        /*foreach($course as $c){
            echo $c->category_name;
            echo "<br/>";
            echo $c->title;
            echo "<br/>";
            echo $c->classroom_name;
            echo "<br/>";
            die();
        }*/
        /*$categories = array();
        foreach($course as $c) {
            if(!isset($categories[$c->category_name])){
                $categories[$c->category_name] = array();
            }
            array_push($categories[$c->category_name], $c->title);
        }*/
        
        $categories = array();
        foreach ($course as $c) {
            $categories[ $c->category_name ][ $c->title ]['course_id'] = $c->id;
            if ($c->classroom_name) {
                $categories[ $c->category_name ][ $c->title ]['classrooms'][$c->classroom_id] = $c->classroom_name;
            }
        }
        //var_dump($categories);
        return $categories;
    }
    

    public function articlesByCourse($id = null) {
    
        /*$article = new Article();
        $course = new Course();
        $course->where('id', $id)->get();
        $article->where_related($course)->get();
        $article->check_last_query();
        foreach($article as $a){
            echo $a->title;
        }*/
        $course = new Course();
        $course->where('id', $id)->get();
        $category = new Category();
        $category->where_related($course)->get();
        $this->load->helper('url');
        $this->load->library('grocery_CRUD');
        $crud = new grocery_CRUD();
        $crud->set_model('custom_query_model');
        $crud->set_table('articles');
        $crud->basic_model->set_query_str('
            SELECT `articles`.*
            FROM (`articles`)
            LEFT OUTER JOIN `courses_articles` courses_articles ON
                    `articles`.`id` = `courses_articles`.`article_id`
            WHERE `courses_articles`.`course_id` = '. $id
        ); 
        //$crud->fields('title','content', 'category_name');
        $crud->unset_jquery();   
        $this->session->set_userdata(array('tempCourseId' => $id));
        $crud->callback_after_insert(array($this, '_relateArticleWithCourse'));
        $output = $crud->render();
        $data['output'] = $output;
        $data['title'] = $category->name . ' / ' . $course->title . ' / ' . 'Articles';
        $data['template'] = 'groceryCrud';
        $this->_loadTemplate($data);
    }
    
    public function _relateArticleWithCourse($post_array, $articleId) {
        $course = new Course();
        $article = new Article();
        $course->where('id', $this->session->userdata('tempCourseId'))->get();
        $article->where('id', $articleId)->get();
        $article->save($course);
        $this->session->unset_userdata('tempCourseId');
    }
    
    public function attachmentsByCourse($id = null) {
        $course = new Course();
        $course->where('id', $id)->get();
        $category = new Category();
        $category->where_related($course)->get();
        $this->load->helper('url');
        $this->load->library('grocery_CRUD');
        $crud = new grocery_CRUD();
        $crud->set_model('custom_query_model');
        $crud->set_table('attachments')            
            ->set_subject('New Attachment')
            ->unset_columns('id');
        $crud->basic_model->set_query_str('
            SELECT `attachments`.*
            FROM (`attachments`)
            LEFT OUTER JOIN `courses_attachments` courses_attachments ON
                    `attachments`.`id` = `courses_attachments`.`attachment_id`
            WHERE `courses_attachments`.`course_id` = '. $id
        ); 
        $crud->add_fields('name','link');
        $crud->edit_fields('name','link');
        $crud->set_field_upload('link','assets/uploads/files');
        $crud->unset_jquery();   
        $this->session->set_userdata(array('tempCourseId' => $id));
        $crud->callback_after_insert(array($this, '_relateAttachmentWithCourse'));
        $output = $crud->render();
        $data['output'] = $output;
        $data['title'] = $category->name . ' / ' . $course->title . ' / ' . 'Attachments';
        $data['template'] = 'groceryCrud';
        $this->_loadTemplate($data);
    }
    
    public function _relateAttachmentWithCourse($post_array, $attachmentId) {
        $attachment = new Attachment();
        $course= new Course();
        $course->where('id', $this->session->userdata('tempCourseId'))->get();
        $attachment->where('id', $attachmentId)->get();
        $attachment->save($course);
        $this->session->unset_userdata('tempCourseId');
    }
    
    public function usersByClassroom($id = null) {
        $this->load->helper('url');
        $user = new User();
        $classroom = new Classroom();
        $course = new Course();
        $category = new Category();
        $classroom->where('id', $id)->get();
        $course->where_related($classroom)->get();
        $user->where_related($classroom)->get();
        $category->where_related($course)->get();
//        $user->check_last_query();
//        foreach($user as $a){
//            echo $a->username;
//        }
//        die();
        $this->load->helper('url');
        $this->load->library('grocery_CRUD');
        $crud = new grocery_CRUD();
        $crud->set_model('custom_query_model');
        $crud->set_table('classrooms')            
            ->set_subject('User To Classroom')
            ->unset_columns('id')
            ->unset_columns('name')
            ->columns('last_name', 'first_name', 'username')
            ->unset_columns('capacity');
        $crud->set_relation_n_n('users', 'classrooms_users', 'users', 'classroom_id', 'user_id', 'last_name','');
        $crud->basic_model->set_query_str('
            SELECT `users`.*
            FROM (`users`)
            LEFT OUTER JOIN `classrooms_users` classrooms_users ON `users`.`id`
                    = `classrooms_users`.`user_id`
            WHERE `classrooms_users`.`classroom_id` = '. $id
        ); 
        $crud->unset_jquery();   
        $output = $crud->render();
        $data['output'] = $output;
        $data['title'] = $category->name . ' / ' . $course->title . ' / ' . $classroom->name;
        $data['template'] = 'groceryCrud';
        $this->_loadTemplate($data);
    }
    
    function _relateArticleWithUser($post_array, $articleId) {
        $user = new User();
        $article = new Article();
        $user->where('id', $this->ion_auth->user()->row()->id)->get();
        $article->where('id', $articleId)->get();
        $article->save($user);
    }
    
    public function settings() {
        $this->load->library('grocery_CRUD');
        $crud = new grocery_CRUD();
        $crud->set_table('settings')
                ->unset_add()
                ->unset_delete()
                ->unset_read()
                ->set_field_upload('site_logo','assets/images')
                ->unset_columns('id');
        $crud->unset_jquery();
        $data['output'] = $crud->render();
        $data['title'] = 'Settings';
        $data['template'] = 'groceryCrud';
        $this->_loadTemplate($data);
    }
    
    public function contact() {
        $this->load->library('grocery_CRUD');
        $crud = new grocery_CRUD();
        $crud->set_table('contacts')
                ->unset_add()
                ->unset_delete()
                ->unset_read()
                ->unset_texteditor('address')
                ->unset_columns('id', 'type');
        $crud->unset_jquery();
        $data['output'] = $crud->render();
        $data['title'] = 'Contact';
        $data['template'] = 'groceryCrud';
        $this->_loadTemplate($data);
    }
    
    public function testimonial() {
        $this->load->library('grocery_CRUD');
        $crud = new grocery_CRUD();
        $crud->set_table('testimonials')
            ->set_field_upload('image','assets/uploads/testimonials')
            ->unset_texteditor('content');
        $crud->unset_jquery();
        $data['output'] = $crud->render();
        $data['title'] = 'Testimonials';
        $data['template'] = 'groceryCrud';
        $this->_loadTemplate($data);
    }
    
    public function banner() {
        $this->load->library('grocery_CRUD');
        $crud = new grocery_CRUD();
        $crud->set_table('banners')
            ->unset_texteditor('link');
        $crud->unset_jquery();
        $data['output'] = $crud->render();
        $data['title'] = 'Banners';
        $data['template'] = 'groceryCrud';
        $this->_loadTemplate($data);
    }
    
    public function slideshow() {
        $this->load->library('grocery_CRUD');
        $crud = new grocery_CRUD();
        $crud->set_table('slides')
            ->unset_texteditor('subtitle')
            ->unset_texteditor('link')
            ->set_field_upload('image','assets/uploads/slides');
        $crud->unset_jquery();
        $data['output'] = $crud->render();
        $data['title'] = 'Slideshow';
        $data['template'] = 'groceryCrud';
        $this->_loadTemplate($data);
    }
    
    public function mailinglist() {
        $this->load->library('grocery_CRUD');
        $crud = new grocery_CRUD();
        $crud->set_table('mailing_list');
        $crud->unset_jquery();
        $data['output'] = $crud->render();
        $data['title'] = 'Mailing List Subscribers';
        $data['template'] = 'groceryCrud';
        $this->_loadTemplate($data);
    }
    
    public function menu() {
        $this->load->library('grocery_CRUD');
        $crud = new grocery_CRUD();
        //$this->load->library('ajax_grocery_CRUD');
        //$crud = new ajax_grocery_CRUD();
        $crud->set_table('menu');
        $crud->set_relation('parent','menu','name');
        $data['output'] = $crud->render();
        $data['title'] = 'Menu Editor';
        $data['template'] = 'groceryCrud';
        $this->_loadTemplate($data);
    }
}

?>